<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\commands;

use app\models\eventType;
use app\models\Plan;
use yii\console\Controller;
use yii\console\ExitCode;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class HelloController extends Controller
{
    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     * @return int Exit code
     */
    public function actionIndex($message = 'hello world')
    {
        echo $message . "\n";

        return ExitCode::OK;
    }

    public function actionSendAlert(){
        date_default_timezone_set('PRC');
        $curHour = date('H');
        if ($curHour > 8 && $curHour < 23) {
            $curPlans = Plan::find()
                ->where(['<=', 'planTime', date('Y-m-d H:i:s')])
                ->orderBy('planTime desc')
                ->limit(2)
                ->asArray()
                ->all();
            if (isset($curPlans[0]['thing']) && !empty($curPlans[0]['thing'])) {
                $command = 'echo "'. $curPlans[0]['thing'] .'" | mailx -s "安排提醒" xiaoqi_no1@163.com 2> /dev/null';
                exec($command);
            } else if ($curPlans[0]['eventId'] !== $curPlans[1]['eventId']) {
                $eventInfo = eventType::find()
                    ->where(['id' => $curPlans[0]['eventId']])
                    ->asArray()
                    ->one();
                $command = 'echo "'. $eventInfo['name'] .'" | mailx -s "事件提醒" xiaoqi_no1@163.com 2> /dev/null';
                exec($command);
            }
        }
    }

    public function actionCopyPrevPlan () {
        $prevDateStr = date('Y-m-') . (date('d') - 1);
        $startTime = $prevDateStr . ' 00:00:00';
        $endTime = $prevDateStr . ' 23:30:00';
        $allPrevPlan = Plan::find()->where(['>=', 'planTime', $startTime])->andWhere(['<', 'planTime', $endTime])->asArray()->all();
        foreach ($allPrevPlan as $key => $value) {
            $hourStr = explode(' ', $value['planTime']);
            $curPlanTime = date('Y-m-d') . ' ' . $hourStr[1];
            $curPlan = Plan::find()->where(['planTime' => $curPlanTime])->one();
            if (empty($curPlan)){
                $curPlan = new Plan();
            }

            $curPlan->eventId = $value['eventId'];
            $curPlan->index = $value['index'];
            $curPlan->planTime = $curPlanTime;
            $curPlan->ctime = time();
            $curPlan->save();
        }
    }
}
